iT邦幫忙

2023 iThome 鐵人賽

0
DevOps

跟著菜鳥手把手用Docker建立服務系列 第 21

Day21 - 菜鳥們把所學的實作做起來 Docker Compose 篇

  • 分享至 

  • xImage
  •  

在前一天我們利用DockerFile來實作 Django + Nginx + Redis + Mysql 這次我們來試試看用 Docker Compose 來實現同樣的系統架構 /images/emoticon/emoticon08.gif


  1. 先建立一個資料夾,裡面分別要有:
    A. docker-compose.yaml
    B. Mysql 資料夾
    C. Redis 資料夾
    D. Nginx 資料夾
    E. Django 資料夾(Code可以從 IT_Project Clone 下來 並且放在Django 資料夾裡)

  2. Myslq
    Dockerfile

    FROM mysql:latest
    
    # COPY my.cnf /etc/my.cnf
    RUN echo '[mysqld]' >> /etc/my.cnf  \
        && echo "general_log = 1" >> /etc/my.cnf \
        && echo "general_log_file = /var/log/mysqld.log" >> /etc/my.cnf \
        && echo "log_output = file" >> /etc/my.cnf
    
     # 指定路徑
     WORKDIR /var/lib/mysql
    
     # 指定容器運行時使用的預設命令
     CMD ["mysqld"]
    

    my.cnf

    [mysqld]
    general_log = 1
    general_log_file = /var/log/mysqld.log
    log_output = file
    
    • Myslq資料夾內容必須要有 DockerFile、my.cnf
  3. Redis
    Dockerfile

    FROM redis:latest
    
    # 複製 redis.conf 檔案到容器中
    COPY redis.conf /usr/local/etc/redis/redis.conf
    
    RUN mkdir /home/redis/
    RUN chmod 777 /home/redis/
    

    redis.conf

    # Redis 7.0 配置文件
    
    # 監聽的端口號
    port 6379
    
    # 監聽的 IP 地址
    #bind 127.0.0.1
    
    # 是否以守護進程模式運行
    #daemonize yes
    
    # 以哪個用戶身份運行 Redis 服務
    user redis
    
    # 密碼設置,設置密碼後需使用該密碼才能訪問 Redis 服務
    requirepass "Your Redis Password"
    
    # 日誌文件的位置和名稱
    logfile /home/redis/redis.log
    
    • Redis資料夾內容必須要有 DockerFile、redis.conf
  4. Nginx
    Dockerfile

    FROM nginx:latest
    
    COPY nginx.conf /etc/nginx/nginx.conf
    COPY my_nginx.conf /etc/nginx/sites-available/
    
    RUN mkdir -p /etc/nginx/sites-enabled/\
        && ln -s /etc/nginx/sites-available/my_nginx.conf /etc/nginx/sites-enabled/
    
    
    CMD ["nginx", "-g", "daemon off;"]
    

    nginx.conf

    user  root;
    worker_processes  1;
    
    error_log  /var/log/nginx/error.log warn;
    pid        /var/run/nginx.pid;
    
    
    events {
        worker_connections  1024;
    }
    
    
    http {
        include       /etc/nginx/mime.types;
        default_type  application/octet-stream;
        log_format  main  '$host $remote_addr - $remote_user [$time_local] '
                          '"$request" $status $body_bytes_sent '
                          '"$http_referer" "$http_user_agent" '
                          '$request_time';
    
    
        access_log  /var/log/nginx/access.log  main;
    
        sendfile        on;
        #tcp_nopush     on;
    
        keepalive_timeout  65;
    
        # Gzip Compression
        gzip on;
        # gzip_min_length 1000;
        gzip_types text/plain application/xml;
        gzip_proxied expired no-cache no-store private auth;
        gzip_vary on;
    
        # include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-available/*;
    }
    
    

    my_ngix.conf

    # the upstream component nginx needs to connect to
    upstream uwsgi {
        # server unix:/web/dj3/web.sock; # using a file socket
        server "Django Container Name":8003;  # using the docker network
    }
    
    # configuration of the server
    server {
        # the port your site will be served on
        listen    80;
        # index  index.html;
        # the domain name it will serve for
        # substitute your machine's IP address or FQDN
        server_name  twtrubiks.com www.twtrubiks.com;
        charset     utf-8;
    
        client_max_body_size 75M;   # adjust to taste
    
    
    
        location /static/ {
           alias /itProject/static/; # your Django project's static files - amend as required
        }
    
        location / {
                uwsgi_pass  uwsgi;
            include     /etc/nginx/uwsgi_params; # the uwsgi_params file you installed
        }
    
    }
    
    
    • Nginx資料夾內容必須要有 DockerFile、nginx.conf、my_nginx.conf
  5. Django
    Dockerfile

    FROM python:3.7
    
    WORKDIR /web
    
    COPY ./itProject /web/
    
    RUN pip install -r requirements.txt
    
    ENTRYPOINT [ "/bin/bash", "docker-entrypoint.sh" ]
    CMD ["uwsgi", "--ini", "uwsgi.ini"]
    

    ItProject 的 settings.py

    CACHES = {
     "default": {
         # 預設使用redis://<redis_host>:<redis_port>/<db_number>
         "BACKEND": "django_redis.cache.RedisCache",
         # 指定redis://IP/第幾個DB
         "LOCATION" : "redis://"Redis Container Name":6379/0",
         "OPTIONS": {
             "CLIENT_CLASS": "django_redis.client.DefaultClient",
             "PASSWORD": "Redis Password",
         },
         'KEY_PREFIX': 'Cache'
     }
    }
    
    DATABASES = {
     'default': {
         #'ENGINE': 'django.db.backends.sqlite3',
         #'NAME': BASE_DIR / 'db.sqlite3',
         'ENGINE' : 'django.db.backends.mysql',
         'NAME' : 'ItDB',
         'USER' : 'root',
         'PASSWORD' : '"Mysql Password"',
         'HOST' :'"Mysql Container Name"',
         'PORT': '3306'
     }
    }
    
    • ItProject 的 settings.py 特別要設定 CACHES 跟 DATABASES
    • Django資料夾內容必須要有 DockerFile、IT_Project
  6. docker-compose.yml

    version: "3.8"
    
    services:
      mysql-server:
        build:
          context: ./mysql
        image: mysql-image:latest
        container_name: mysql-contianer
        environment:
          - MYSQL_DATABASE=ItDB
          - MYSQL_USER=ITUser
          - MYSQL_PASSWORD="Mysql Password"
          - MYSQL_ROOT_PASSWORD="Mysql Root Password"
        volumes:
          - mysqlVolumes:/var/log  
        networks:
          - composeBridge
        healthcheck:
          test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
          interval: 15s
          timeout: 5s
          retries: 3
    
      redis-server:
        build:
          context: ./redis
        image: redis-image:latest
        container_name: redis-container
        command: redis-server /usr/local/etc/redis/redis.conf
        depends_on: 
          - mysql-server
        networks:
          - composeBridge
    
      django-python-server:
        build:
          context: ./DjangoWeb
        image: django-python-image:latest 
        container_name: django-python-container
        depends_on: 
          mysql-server:
            condition: service_healthy
        networks:
          - composeBridge
    
      nginx-server:
        build:
          context: ./nginx
        image: nginx-image:latest
        container_name: nginx-container
        ports:
          - "127.0.0.1:8003:80"
        depends_on:
          - django-python-server
        networks:
          - composeBridge
    
       volumes: 
         mysqlVolumes:
           name: mysql_volumes
    
       networks:
         composeBridge:
           name: compose_bridge
           driver: bridge
    
    

啟動 Docker Container
docker-compose up -d

呈現結果
輸入127.0.0.1:8003/member/create
https://ithelp.ithome.com.tw/upload/images/20240124/20158512c6n9Sd9BcW.png

輸入127.0.0.1:8003/member/read
https://ithelp.ithome.com.tw/upload/images/20240124/20158512uNpAlUtD3G.png


可以跟前一天的Day20 -菜鳥們把所學的實作做起來 DockerFile 篇比較,透過Docker Compose去實作,會比較更簡潔有序,而且也更好維護/images/emoticon/emoticon07.gif


上一篇
Day20 - 菜鳥們把所學的實作做起來 DockerFile 篇
下一篇
Day22 - 菜鳥們一起探討實作的 Docker Compose
系列文
跟著菜鳥手把手用Docker建立服務30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言